/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.DaftarModul;
import model.Modul;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Aspire
 */
public class UploadModul extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String TMP_DIR_PATH = "c:/tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "Files";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        System.out.println(realPath);
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException, Exception {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setRepository(tmpDir);
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        String page = request.getParameter("page");
        RequestDispatcher dis = null;
        List<Modul> moduls = new ArrayList<Modul>();
        HttpSession session = request.getSession();

        DaftarModul dm = new DaftarModul();
        if (page != null) {
            if (page.equals("upload")) {
                session.removeAttribute("error");
                Modul modul = new Modul();
                Long idModul = Long.parseLong(request.getParameter("idModul"));
                modul = dm.getModul(idModul);
                session.setAttribute("mdl", modul);
                dis = request.getRequestDispatcher("fileModul.jsp");
                dis.forward(request, response);
            } else if (page.equals("uploaded")) {
                session.removeAttribute("error");
                Modul modul = new Modul();
                List items = uploadHandler.parseRequest(request);
                Iterator itr = items.iterator();

                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();
                    File file = new File(destinationDir, item.getName());
                    if (file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("pdf")
                            || file.getName().substring(file.getName().length() - 3, file.getName().length()).equals("PDF")) {
                        item.write(file);
                        String filepath = DESTINATION_DIR_PATH + "/" + file.getName();
                        modul = (Modul) session.getAttribute("mdl");
                        modul.setFile(filepath);
                        dm.edit(modul);
                    } else {
                        session.setAttribute("error", "format file harus .pdf atau .PDF");
                        dis = request.getRequestDispatcher("fileModul.jsp");
                        dis.forward(request, response);
                    }
                }
                moduls = dm.getModuls();
                request.setAttribute("moduls", moduls);
                dis = request.getRequestDispatcher("daftarModul.jsp");
                dis.forward(request, response);
            } else if (page.equals("add")) {
                session.removeAttribute("error");
                dis = request.getRequestDispatcher("tambahModul.jsp");
                dis.forward(request, response);
            } else if (page.equals("added")) {
                session.removeAttribute("error");
                Modul modul = new Modul();
                String judulModul = request.getParameter("judulModul");
                String keterangan = request.getParameter("keterangan");
                modul.setJudulModul(judulModul);
                modul.setKeteranganModul(keterangan);
                if (judulModul.equals("") || keterangan.equals("")) {
                    session.setAttribute("error", "* masih ada field kosong");
                    dis = request.getRequestDispatcher("tambahModul.jsp");
                    dis.forward(request, response);
                } else {
                    dm.create(modul);
                    moduls = dm.getModuls();
                    request.setAttribute("moduls", moduls);
                    dis = request.getRequestDispatcher("daftarModul.jsp");
                    dis.forward(request, response);
                }
            } else if (page.equals("show")) {
                session.removeAttribute("error");
                if (session.getAttribute("uname") != null) {
                    if (request.getParameter("idModul") == null) {
                        moduls = dm.getModuls();
                        request.setAttribute("moduls", moduls);
                        dis = request.getRequestDispatcher("daftarModul.jsp");
                        dis.forward(request, response);
                    } else {
                        Long id = Long.parseLong(request.getParameter("idModul"));
                        dm.deleteModul(id);
                        moduls = dm.getModuls();
                        request.setAttribute("moduls", moduls);
                        dis = request.getRequestDispatcher("daftarModul.jsp");
                        dis.forward(request, response);
                    }
                } else {
                    session.removeAttribute("error");
                    session.setAttribute("error", "anda sudah logout");
                    dis = request.getRequestDispatcher("index.jsp");
                    dis.forward(request, response);
                }
            } else if (page.equals("view")) {
                session.removeAttribute("error");
                moduls = dm.getModuls();
                request.setAttribute("moduls", moduls);
                dis = request.getRequestDispatcher("DaftarModulUser.jsp");
                dis.forward(request, response);
            }

        } else {
            dis = request.getRequestDispatcher("index.jsp");
            dis.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadModul.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(UploadModul.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadModul.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(UploadModul.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
